package com.sdcqjy.property.lawRegulations;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sdcqjy.mylibrary.Logger;
import com.sdcqjy.mylibrary.OtherUtils;
import com.sdcqjy.mylibrary.widget.PublicDialog;
import com.sdcqjy.mylibrary.widget.ShowToast;
import com.sdcqjy.property.R;
import com.sdcqjy.property.activity.WebViewActivity;
import com.sdcqjy.property.base.BaseService;
import com.sdcqjy.property.base.SimpleBaseActivity;
import com.sdcqjy.property.mode.LawRegulationsDetailsMode;
import com.sdcqjy.property.presenter.LawRegulationsDetailsPresenter;
import com.sdcqjy.property.presenter.contract.LawRegulationsDetailsContract;
import com.sdcqjy.property.widget.BookMarkView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 磁磁帅 on 2018/7/8.
 * 功能：
 */
public class LawRegulationsDetailsActivity extends SimpleBaseActivity<LawRegulationsDetailsPresenter>
        implements LawRegulationsDetailsContract.View, BookMarkView.OnPopupWindowListener {
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.textTitle)
    TextView textTitle;
    @BindView(R.id.et_key)
    EditText etKey;
    @BindView(R.id.tv_position)
    TextView tvPosition;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.tool_bar)
    Toolbar toolBar;
    private LawRegulationsDetailsMode mode;
    private BookMarkView bookMarkView;

    public static void open(Context context, LawRegulationsDetailsMode data) {
        Intent intent = new Intent(context, LawRegulationsDetailsActivity.class);
        intent.putExtra("mode", new Gson().toJson(data));
        context.startActivity(intent);
    }

    @SuppressLint("JavascriptInterface")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lawregulations_details);
        ButterKnife.bind(this);
        presenter = new LawRegulationsDetailsPresenter(this);
        Intent intent = getIntent();
        String json = intent.getStringExtra("mode");
        if (!TextUtils.isEmpty(json))
            mode = new Gson().fromJson(json, LawRegulationsDetailsMode.class);

        WebSettings settings = webView.getSettings();

        //缩放开关，设置此属性，仅支持双击缩放，不支持触摸缩放
        settings.setSupportZoom(true);
        //设置是否可缩放，会出现缩放工具（若为true则上面的设值也默认为true）
        settings.setBuiltInZoomControls(true);
        //隐藏缩放工具
        settings.setDisplayZoomControls(false);
//        settings.setDefaultZoom(WebSettings.ZoomDensity.FAR);// 默认缩放模式
//        settings.setUseWideViewPort(true);  //为图片添加放大缩小功能

        webView.setBackgroundColor(0xffFFffFF);

        settings.setJavaScriptEnabled(true);
        //webView.addJavascriptInterface(new AppOpert(), "androidObj");
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccess(true); //设置可以访问文件
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        //settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.out(url);
                if (url.equals("about:blank") || url.startsWith("mailto:")) {
                } else if (url.startsWith("tel:")) {//电话
                    OtherUtils.callTelOfUri(getActivity(), url);
                } else {
                    webView.loadUrl(url);
                }
                return true;
            }

            public void onPageFinished(WebView view, String url) {
                //执行图片缩放
//                if (android.os.Build.VERSION.SDK_INT >= 21) {
//                    zoom();
//                } else {
                webView.loadUrl("javascript:" + WebViewActivity.FullAll);
                webView.loadUrl("javascript:fullscreen()");
//                }
            }
        });
        webView.setWebChromeClient(new MyWebChromeClient());
        webView.setDownloadListener((url1, userAgent, contentDisposition, mimetype, contentLength) -> {
            Uri uri = Uri.parse(url1);
            Intent intent1 = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent1);
            onBackPressed();
        });
        //“file:///android_asset/sample.html”
//        if (isHtml)
//            webView.loadDataWithBaseURL(BaseService.ImgURL, url, "text/html", "utf-8", null);
//        else webView.loadUrl(url);
//        if (!TextUtils.isEmpty(title)) textTitle.setText(title);
//        webView.findAllAsync(content);
//        webView.clearMatches();
        llTop.setVisibility(View.GONE);
        setSupportActionBar(toolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.mipmap.fanhui);
        toolBar.setNavigationOnClickListener(view -> onBackPressed());
    }

    protected void asynRun() {
        if (mode == null) {
            finish();
            return;
        }
        webView.loadDataWithBaseURL(BaseService.ImgURL, mode.contect, "text/html", "utf-8", null);
        textTitle.setText(mode.title);

        //输入文本自动查询
        etKey.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            public void afterTextChanged(Editable key) {
                //搜索点击
                webView.findAllAsync(key.toString());
                webView.setFindListener(new WebView.FindListener() {
                    public void onFindResultReceived(int position, int all, boolean b) {
                        tvPosition.setText("(" + (position + 1) + "/" + all + ")");
                    }
                });
            }
        });
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_lawregul, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.btnShu) {
            if (isLogin()) presenter.getBookMark();
        } else if (item.getItemId() == R.id.btnSou) {
            llTop.setVisibility(View.VISIBLE);
        }
        return super.onOptionsItemSelected(item);
    }

    public void getBookMarkRet(List<LawRegulationsDetailsMode> data) {
        if (bookMarkView == null) {
            bookMarkView = new BookMarkView(getActivity())
                    .setOnPopupWindowListener(this);
        }
        bookMarkView.setModeList(data)
                .setBookMark(mode)
                .showPopupWindow(toolBar);
    }

    public void addBookMark() {
        if (isLogin()) presenter.addBookMark(mode);
    }

    //跳转
    public void toBookMark(LawRegulationsDetailsMode mode) {
        mode.id = mode.lawID;
        LawRegulationsDetailsActivity.open(getActivity(), mode);
        finish();
    }

    private LawRegulationsDetailsMode deleBookMarkMode;

    public void deleBookMark(LawRegulationsDetailsMode mode) {
        deleBookMarkMode = mode;
        PublicDialog dialog = new PublicDialog(getActivity());
        dialog.setTitle(null);
        dialog.setContent(R.string.querensanchu);
        dialog.setOnPublicDialogClick(new PublicDialog.OnPublicDialogClick() {
            public void onConfirmClick() {
                if (isLogin()) presenter.delBookMark(deleBookMarkMode);
            }

            public void onCancelClick() {
            }
        });
        dialog.show();
    }

    public void addBookMarkSucc() {
        ShowToast.alertShortOfWhite(getActivity(), R.string.tianjiachenggong);
        if (bookMarkView != null) {
            mode.lawID = mode.id;
            bookMarkView.addBookMark(mode);
        }
    }

    public void delBookMarkSucc() {
        ShowToast.alertShortOfWhite(getActivity(), R.string.sanchuchenggong);
        if (bookMarkView != null && deleBookMarkMode != null) {
            bookMarkView.removeBookMark(deleBookMarkMode);
            deleBookMarkMode = null;
        }
    }

    @OnClick(R.id.btn_pre)
    public void onBtnPreClicked() {
        webView.findNext(false);
    }

    @OnClick(R.id.btn_next)
    public void onBtnNextClicked() {
        webView.findNext(true);
    }

    @OnClick(R.id.closeBtn)
    public void onCloseBtnClicked() {
        etKey.setText("");
        llTop.setVisibility(View.GONE);
    }
    //    public boolean onKeyUp(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (webView.canGoBack()) {
//                webView.goBack();// 返回前一个页面
//            } else onBackPressed();
//            return true;
//        }
//        return super.onKeyUp(keyCode, event);
//    }

    /**
     * 继承WebChromeClient类
     * 对js弹出框时间进行处理
     */
    final class MyWebChromeClient extends WebChromeClient {

        /**
         * 处理alert弹出框
         */
        @Override
        public boolean onJsAlert(WebView view, String url,
                                 String message, JsResult result) {
            new AlertDialog.Builder(getActivity()).
                    setTitle("Alert").setMessage(message).setPositiveButton("OK",
                    (arg0, arg1) -> {
                        //TODO
                    }).create().show();
            result.confirm();
            return true;
        }

        /**
         * 处理confirm弹出框
         */
        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   JsResult result) {
            result.confirm();
            return super.onJsConfirm(view, url, message, result);
        }

        /**
         * 处理prompt弹出框
         */
        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, JsPromptResult result) {
            result.confirm();
            return super.onJsPrompt(view, url, message, message, result);
        }
    }
}
